package net.documentshare.question;

import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import net.documentshare.i.ICommonBeanAware;
import net.documentshare.impl.AbstractAttention;
import net.documentshare.mytag.ETagType;
import net.documentshare.mytag.MyTagUtils;
import net.documentshare.utils.ItSiteUtil;
import net.simpleframework.ado.IDataObjectValue;
import net.simpleframework.ado.db.IQueryEntitySet;
import net.simpleframework.ado.db.ITableEntityManager;
import net.simpleframework.ado.db.event.TableEntityAdapter;
import net.simpleframework.content.AbstractMgrToolsAction;
import net.simpleframework.content.IContentApplicationModule;
import net.simpleframework.core.id.LongID;
import net.simpleframework.organization.IJob;
import net.simpleframework.organization.account.AccountContext;
import net.simpleframework.organization.account.AccountSession;
import net.simpleframework.organization.account.IAccount;
import net.simpleframework.util.ConvertUtils;
import net.simpleframework.util.LocaleI18n;
import net.simpleframework.util.StringUtils;
import net.simpleframework.web.page.IForward;
import net.simpleframework.web.page.UrlForward;
import net.simpleframework.web.page.component.ComponentParameter;
import net.simpleframework.web.page.component.base.ajaxrequest.AjaxRequestBean;
import net.simpleframework.web.page.component.ui.validatecode.DefaultValidateCodeHandle;

public class QuestionAjaxHandle extends AbstractMgrToolsAction {
	public IForward editUrl(final ComponentParameter compParameter) throws Exception {
		return new UrlForward(QuestionUtils.deploy + "/question_add.jsp");
	}

	@Override
	public Object getBeanProperty(ComponentParameter compParameter, String beanProperty) {
		if ("jobExecute".equals(beanProperty)) {
			return IJob.sj_account_normal;
		}
		return super.getBeanProperty(compParameter, beanProperty);
	}

	public IForward osRef(final ComponentParameter compParameter) throws Exception {
		final AjaxRequestBean ajaxBean = (AjaxRequestBean) compParameter.componentBean;
		ajaxBean.setUpdateContainerId(compParameter.getRequestParameter("refId") + "_");
		return new UrlForward(QuestionUtils.deploy + "/ref/os_list.jsp");
	}

	@Override
	public IContentApplicationModule getApplicationModule() {
		return QuestionUtils.applicationModule;
	}

	/**
	 * 没有最近答案
	 * @param compParameter
	 * @return
	 */
	public IForward notGoodAnswerAct(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {
			@Override
			public void doAction(final Map<String, Object> json) {
				final QuestionBean questionBean = QuestionUtils.getQuestionBean(compParameter);
				if (questionBean != null) {
					if (ItSiteUtil.isManageOrSelf(compParameter, QuestionUtils.applicationModule, questionBean.getUserId())) {
						questionBean.setStatus(EQuestionStatus.noGoodAnswer);
						QuestionUtils.applicationModule.doUpdate(new Object[] { "status" }, questionBean);
						json.put("jsCallback", "$Actions.loc('" + QuestionUtils.applicationModule.getViewUrl(questionBean.getId()) + "');");
					}
				}
			}
		});
	}

	/**
	 * 投票
	 * @param compParameter
	 * @return
	 */
	public IForward questionVote(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {
			@Override
			public void doAction(final Map<String, Object> json) {
				final QuestionBean questionBean = QuestionUtils.getQuestionBean(compParameter);
				if (questionBean != null) {
					ICommonBeanAware.Utils.updateVotes(compParameter, QuestionUtils.applicationModule.getDataObjectManager(), questionBean, json);
				}
			}
		});
	}

	public IForward indexRebuild(final ComponentParameter compParameter) {
		QuestionUtils.applicationModule.createLuceneManager(compParameter).rebuildAll(true);
		return jsonForward(compParameter, new JsonCallback() {
			@Override
			public void doAction(final Map<String, Object> json) {
				json.put("info", LocaleI18n.getMessage("manager_tools.6"));
			}
		});
	}

	@Override
	protected void doStatRebuild() {
		QuestionUtils.doStatRebuild();
	}

	/**
	 * 关注
	 * 
	 * @param compParameter
	 * @return
	 */
	public IForward questionAttention(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {

			@Override
			public void doAction(final Map<String, Object> json) throws Exception {
				AbstractAttention.Utils.updateAttention(QuestionUtils.questionId, compParameter, QuestionBean.class, QuestionAttention.class,
						QuestionUtils.applicationModule, json);
			}
		});
	}

	/**
	 * 高级属性
	 * 
	 * @param compParameter
	 * @return
	 */
	public IForward questionAttrSave(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {

			@Override
			public void doAction(final Map<String, Object> json) throws Exception {
				if (ItSiteUtil.isManage(compParameter, QuestionUtils.applicationModule)) {
					final QuestionBean questionBean = QuestionUtils.getQuestionBean(compParameter);
					if (questionBean != null) {
					}
				}
			}
		});
	}

	/**
	 * 删除发布的开源项目
	 */
	public IForward questionDelete(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {

			@Override
			public void doAction(final Map<String, Object> json) throws Exception {
				if (ItSiteUtil.isLogin(compParameter)) {
					final QuestionBean questionBean = QuestionUtils.getQuestionBean(compParameter);
					if (questionBean != null && ItSiteUtil.isManageOrSelf(compParameter, QuestionUtils.applicationModule, questionBean.getUserId())) {
						if (questionBean.getRemarks() > 0) {
							json.put("act", LocaleI18n.getMessage("it_delete_remark"));
							return;
						}
						// 只有自己和管理员可以删除
						if (ItSiteUtil.isManageOrSelf(compParameter, QuestionUtils.applicationModule, questionBean.getUserId())) {
							QuestionUtils.applicationModule.doDelete(questionBean, new TableEntityAdapter() {
								@Override
								public void afterDelete(ITableEntityManager manager, IDataObjectValue dataObjectValue) {
									QuestionUtils.applicationModule.deleteAttentions(questionBean.getId());
									QuestionUtils.applicationModule.createLuceneManager(compParameter).deleteDocumentBackground(
											dataObjectValue.getValues());
									MyTagUtils.deleteRTags(dataObjectValue.getValues());

									//先删除所有的关联的开源项目
									final IQueryEntitySet<QuestionProjectBean> qs = QuestionUtils.applicationModule
											.queryQuestionProjectBeans(questionBean.getId());
									if (qs != null) {
										QuestionProjectBean qp = null;
										while ((qp = qs.next()) != null) {
											QuestionUtils.applicationModule.doDelete(qp);
										}
									}
								}
							});
						} else {
							json.put("act", LocaleI18n.getMessage("it_illegal"));
							return;
						}
					}
				}
			}
		});
	}

	final static String[] q_ps = { "q_p1_value", "q_p2_value", "q_p3_value" };

	/**
	 * 问题补充
	 * @param compParameter
	 * @return
	 */
	public IForward questionExtSave(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {
			@Override
			public void doAction(Map<String, Object> json) throws Exception {
				if (ItSiteUtil.isLogin(compParameter)) {
					final QuestionExtBean questionExtBean = new QuestionExtBean();
					questionExtBean.setContent(compParameter.getRequestParameter("qExt_content"));
					questionExtBean.setQuestionId(new LongID(compParameter.getRequestParameter("questionId")));
					QuestionUtils.applicationModule.doUpdate(questionExtBean);
				}
			}
		});
	}

	/**
	 * 删除
	 * @param compParameter
	 * @return
	 */
	public IForward questionExtDelete(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {
			@Override
			public void doAction(Map<String, Object> json) throws Exception {
				if (ItSiteUtil.isLogin(compParameter)) {
					QuestionUtils.applicationModule.doDelete(QuestionExtBean.class, compParameter.getRequestParameter("questionExtId"));
				}
			}
		});
	}

	/**
	 * 发布开源项目
	 */
	public IForward questionSave(final ComponentParameter compParameter) throws Exception {
		return jsonForward(compParameter, new JsonCallback() {
			QuestionBean questionBean = null;

			@Override
			public void doAction(final Map<String, Object> json) throws Exception {
				if (!DefaultValidateCodeHandle.isValidateCode(compParameter.request, "textQuestionEditorValidateCode")) {
					json.put("validateCode", DefaultValidateCodeHandle.getErrorString());
				} else {
					questionBean = QuestionUtils.getQuestionBean(compParameter);
					final IAccount account = AccountSession.getLogin(compParameter.getSession());
					if (questionBean == null) {
						questionBean = new QuestionBean();
						questionBean.setAttentions(1);
						questionBean.setUserId(account.getId());
					}
					questionBean.setLastUserId(account.getId());
					questionBean.setModifyDate(new Date());
					questionBean.setContent(ItSiteUtil.doDownloadContent(compParameter, compParameter.getRequestParameter("q_content")));
					questionBean.setTitle(compParameter.getRequestParameter("q_title"));
					questionBean.setLimitTime(ConvertUtils.toDate(compParameter.getRequestParameter("q_limitTime"), ItSiteUtil.yyyyMMdd_HH));
					questionBean.setReward(ConvertUtils.toInt(compParameter.getRequestParameter("q_reward"), 0));
					questionBean.setKeywords(compParameter.getRequestParameter("q_keywords"));
					questionBean.setEmail(ConvertUtils.toBoolean(compParameter.getRequestParameter("q_email"), false));
					QuestionUtils.applicationModule.doUpdate(questionBean, new TableEntityAdapter() {
						@Override
						public void afterInsert(ITableEntityManager manager, Object[] objects) {
							final QuestionAttention attention = new QuestionAttention();
							attention.setUserId(account.getId());
							attention.setQuestionId(questionBean.getId());
							attention.setCreateDate(new Date());
							QuestionUtils.applicationModule.doUpdate(attention);

							MyTagUtils.syncTags(ETagType.question, LongID.zero, questionBean.getKeywords(), questionBean.getId());
							updateRefProject();
							//增加积分和日志
							AccountContext.update(account, "question_add", questionBean.getId());
						}

						private void updateRefProject() {
							try {
								//先删除所有的关联的开源项目

								final IQueryEntitySet<QuestionProjectBean> qs = QuestionUtils.applicationModule
										.queryQuestionProjectBeans(questionBean.getId());
								if (qs != null) {
									QuestionProjectBean csp = null;
									while ((csp = qs.next()) != null) {
										QuestionUtils.applicationModule.doDelete(csp);
									}
								}
								final Set<String> set = new HashSet<String>();
								for (final String q_p : q_ps) {
									final String q_p_value = compParameter.getRequestParameter(q_p);
									if (StringUtils.hasText(q_p_value)) {
										if (set.contains(q_p_value)) {
											continue;
										}
										set.add(q_p_value);
										final QuestionProjectBean csp = new QuestionProjectBean();
										csp.setQuestionId(questionBean.getId());
										csp.setProjectId(new LongID(q_p_value));
										try {
											QuestionUtils.applicationModule.doUpdate(csp);
										} catch (Exception e) {
										}
									}
								}
							} catch (Exception e) {
							}
						}

						@Override
						public void afterUpdate(ITableEntityManager manager, Object[] objects) {
							updateRefProject();
							MyTagUtils.syncTags(ETagType.question, LongID.zero, questionBean.getKeywords(), questionBean.getId());
						}
					});
					json.put("close", compParameter.getRequestParameter("close"));
					json.put("questionId", questionBean.getId().getValue());
					QuestionUtils.applicationModule.createLuceneManager(compParameter).objects2DocumentsBackground(questionBean);
				}
			}
		});
	}
}
